<template>
  <div class="policy-items-wrap table-gl-w">
    <div class="search-w table-filter-form">
      <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getTableData">
        <template #headerLeft>
          <a-space>
            <p>共计 {{ total }} 条</p>
            <a-button v-if="$authPass('policy-targeting.operation')" class="gray-outline" size="medium" @click="changeStateBatch(0, '暂停')">暂停</a-button>
            <a-button v-if="$authPass('policy-targeting.operation')" class="gray-outline" size="medium" @click="changeStateBatch(2, '移除')">移除</a-button>
            <a-button v-if="$authPass('policy-targeting.operation')" class="gray-outline" size="medium" @click="changeStateBatch(1, '开启')">开启</a-button>
          </a-space>
        </template>
        <template #tableBody>
          <a-table class="table-two-line" ref="tableRef" row-key="id" :loading="tableLoading" @selection-change="selectColumn" :row-selection="rowSelection" :bordered="false" :data="tableList" :scroll="{ y: '100%' }" size="mini" :pagination="false">
            <template #columns>
              <a-table-column title="店铺">
                <template #cell="{ record }">
                  {{ record.shopName }}
                </template>
              </a-table-column>
              <a-table-column title="应用对象">
                <template #cell="{ record }">
                  <p>{{ TargetingType[record.targetingType] }}</p>
                  <p>{{ record.policyApplicationName }}</p>
                </template>
              </a-table-column>
              <a-table-column title="广告类型">
                <template #cell="{ record }">
                  <p>{{ AdTypes[record.adType] }}</p>
                </template>
              </a-table-column>
              <a-table-column title="广告组合/广告活动">
                <template #cell="{ record }">
                  <p>{{ record.portfolioName }}</p>
                  <p>{{ record.campaignName }}</p>
                </template>
              </a-table-column>
              <a-table-column title="基准预算/竞价">
                <template #cell="{ record }">
                  <p>${{ record.campaignBudgetAmount }}</p>
                  <p>${{ record.referenceAmount }}</p>
                </template>
              </a-table-column>
              <a-table-column title="销售员">
                <template #cell="{ record }">
                  <p>{{ record.ownerName || '--' }}</p>
                </template>
              </a-table-column>
              <a-table-column title="分时策略" :width="250">
                <template #cell="{ record }">
                  <div class="flex-c-sb">
                    <div>
                      <div class="flex-c">
                        <a-popconfirm :content="`确定是否${record.state === 0 ? '开启' : '暂停'}策略`" @ok="changeState(record)" type="warning">
                          <a-switch :disabled="!$authPass('policy-targeting.operation')" v-model="record.state" :checked-value="1" :unchecked-value="0" size="small" style="margin-right: 5px" :beforeChange="handleChangeIntercept" />
                        </a-popconfirm>
                        <p>{{ PolicyType[record.policyType] }}</p>
                      </div>
                      <p>{{ record.policyName }}</p>
                    </div>
                    <a-popconfirm v-if="$authPass('policy-targeting.operation')" v-model:popup-visible="record.isPopup" content="确定是否删除策略?" @ok="deleteItem(record)" type="error">
                      <icon-delete :class="record.isPopup ? 'popup-edit-icon icon-delete highlight' : 'icon-delete highlight popup-edit-icon popup-edit-icon-hover'" />
                    </a-popconfirm>
                  </div>
                </template>
              </a-table-column>
              <!-- <a-table-column title="操作" :width="80">
                <template #cell>
                  <a-button type="text">日志</a-button>
                </template>
              </a-table-column> -->
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, watchEffect, onMounted } from 'vue'
  import FilterTable from '@/components/TableFilter.vue'
  import { getPolicyList, operationPolicyTargeting } from '@/api/advert'
  import TableWrap from '@/components/TableWrap.vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import { TargetingType, AdTypes, PolicyType } from '../types'
  import { FilterTableItem } from '@/types/components'
  onMounted(() => {
    getTableData()
  })

  const props = defineProps({
    markedtList: {
      type: Array,
      default: () => [],
    },
    shopList: {
      type: Array,
      default: () => [],
    },
    userList: {
      type: Array,
      default: () => [],
    },
  })
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any
  const filterItem = ref<Array<FilterTableItem>>([
    {
      key: 'marketplaceIds',
      label: '站点',
      value: ref(),
      type: 'select_multiple',
      width: 120,
      optionItems: [],
    },
    {
      key: 'shopIds',
      label: '店铺',
      value: ref(),
      type: 'select_multiple',
      width: 120,
      optionItems: [],
    },
    {
      key: 'adType',
      label: '广告类型',
      value: ref(),
      type: 'select',
      width: 120,
      optionItems: [
        {
          label: '商品广告',
          value: 'SPONSORED_PRODUCTS',
        },
        {
          label: '品牌广告',
          value: 'SPONSORED_BRANDS',
        },
        {
          label: '展示广告',
          value: 'SPONSORED_DISPLAY',
        },
      ],
    },
    {
      key: 'policyType',
      label: '分时策略类型',
      value: ref(),
      type: 'select',
      width: 140,
      optionItems: [
        {
          label: '分时调整预算',
          value: 'BUDGET_POLICY',
        },
        {
          label: '分时调整竞价',
          value: 'BIDDING_POLICY',
        },
        {
          label: '分时启停',
          value: 'SWITCH_POLICY',
        },
        {
          label: '分时调整广告位',
          value: 'TARGETING_POLICY',
        },
      ],
    },
    {
      key: 'ownerId',
      label: '销售员',
      value: ref(),
      type: 'select',
      width: 120,
      optionItems: [],
    },
    {
      key: 'policyApplicationName',
      label: '应用对象名称',
      value: ref(),
      type: 'input_search',
      width: 150,
    },
    {
      key: 'policyName',
      label: '策略名称',
      value: ref(),
      type: 'input_search',
      width: 150,
    },
  ])
  let searchVal = ref({
    pageSize: 20,
    pageNum: 1,
  })
  const total = ref(0)
  const tableLoading = ref(false)
  const tableList = ref<Array<any>>([])
  const selectIds = ref([])
  const filterData = ref<any>({})

  function selectColumn(val: any) {
    selectIds.value = val
  }
  // 通过条件查询用户列表
  function searchByVal(info: any) {
    searchVal.value.pageNum = 1
    filterData.value = JSON.parse(JSON.stringify(info)) || {}
    filterData.value.marketplaceIds = filterData.value.marketplaceIds ? filterData.value.marketplaceIds.split(',') : undefined
    filterData.value.shopIds = filterData.value.shopIds ? filterData.value.shopIds.split(',') : undefined
    getTableData()
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableData()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableData()
  }

  // 获取列表数据
  async function getTableData() {
    let params = {
      pageNum: searchVal.value.pageNum,
      pageSize: searchVal.value.pageSize,
      ...filterData.value,
    }
    tableLoading.value = true
    const res: any = await getPolicyList(params)
    tableLoading.value = false
    tableList.value = res?.data?.data || []
    total.value = res?.data?.total || 0
  }
  // 批量更改
  function changeStateBatch(status: number, statusText: string) {
    if (!selectIds.value.length) {
      return Message.error('请选择应用明细')
    }
    Modal.confirm({
      title: '提示',
      content: `请再次确认，${statusText}选中的分时应用明细`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: async () => {
        let res: any = await operationPolicyTargeting({
          policyTargetingIds: selectIds.value,
          state: status,
        })
        if (res) {
          Message.success(`${statusText}成功`)
          getTableData()
        }
      },
    })
  }
  // 删除
  async function deleteItem(row: any) {
    let res: any = await operationPolicyTargeting({
      policyTargetingIds: [row.id],
      state: 2,
    })
    if (res) {
      getTableData()
    }
  }
  // 拦截自动切换
  async function handleChangeIntercept() {
    return false
  }
  // 单个切换状态
  async function changeState(row: any) {
    let state = row.state === 0 ? 1 : 0
    let res: any = await operationPolicyTargeting({
      policyTargetingIds: [row.id],
      state: state,
    })
    if (res) {
      getTableData()
    }
  }
  watchEffect(() => {
    if (props.markedtList?.length) {
      filterItem.value[0].optionItems = props.markedtList
    }
    if (props.shopList?.length) {
      filterItem.value[1].optionItems = props.shopList
    }
    if (props.userList?.length) {
      filterItem.value[4].optionItems = props.userList
    }
  })
</script>
<style lang="less" scoped>
  .policy-items-wrap {
    height: calc(100vh - @menuAndTabHeight) !important;
  }
  .icon-delete {
    font-size: 16px;
    flex-shrink: 0;
    margin-left: 10px;
    cursor: pointer;
  }
</style>
